<template>
	<view class="page">
		<scroll-view @scrolltoupper="upperthreshold" class="scroll-view" scroll-y :scroll-top="top">
			<view id="sctop" style="padding: 30rpx 30rpx 240rpx;">
				<view v-if="isload" class="flex-ju-c">
					<image class="width50" mode="widthFix" src="/static/run.gif"></image>
				</view>
				<template v-for="(item,index) in list" :key="index">
					<view class="flex-ju-c flex size24">
					 <template v-if="index > 0">
						 <template v-if="item.payload.time - list[index-1].payload.time > 300000">
						 <view  class="bgdadada colorfff pg5-10">
							 {{formatTime(item.payload.time)}}
							 </view>
						 </template>
					 </template>
					</view>
					<view class="message" :class="[item.payload.type]">
						<image :src="item.payload.tuser.avatar?item.payload.tuser.avatar:'/static/mo.png'"
							v-if="item.payload.type == 'friend'" class="avatar" ></image>
					
						<!-- <view class="content" v-if="item.payload.messageType == 'image'">
							<image :src="item.payload.content" mode="widthFix"></image>
						</view> -->
						<view class="content" v-if="item.payload.messageType == 'image'">
							<view @click="preImage(itesm)" v-for="(itesm,k) in item.payload.content" :key="k">
								<image :src="itesm" mode="widthFix"></image>
							</view>
						</view>
						
						<view class="content" v-else>
							{{ item.payload.content }}
						</view>
						<image :src="item.payload.user.avatar?item.payload.user.avatar:'/static/mo.png'"
							v-if="item.payload.type == 'self'" class="avatar"></image>
					</view>
				</template>
				
			</view>
		</scroll-view>
		<view @click="showbut = false" v-if="showbut" class=" height70vh posiab top0 width100vw">
			
		</view>
		<view class="tool">
			<view class="flex-a-i">
				<!-- <image src="/static/yuyin.png" mode="widthFix" class="thumb mr20" @click="yuyins"></image> -->
				<textarea confirm-type="done" cursor-spacing="20" auto-height v-model="content" class="input"
					@confirm="send"></textarea>
				<!-- <image src="/static/biaoqing.png" mode="widthFix" class="thumb" @click="chooseImage"></image> -->
				<view v-show="content" @click="send" class="bg27a752 wh100-60 colorfff ra5 size24 flex-ju-c ml20">
					发送
				</view>
				<image v-show="!content" src="/static/gengduo.png" mode="widthFix" class="thumb ml20"
					@click="chooseImage"></image>
			</view>
			
			<view v-if="showbut" class="flex-a-i size24 border-tf6f7f8 mt20 pt20">
				<view @click="setimg" class="center">
					<view class="bgf6f7f8 wh100-100 flex-ju-c mb10 ra10">
						<uni-icons size="40" type="image"></uni-icons>
					</view>
					照片
				</view>
				<!-- <view class="center ml30">
					<view class="bgf6f7f8 wh100-100 flex-ju-c mb10 ra10">
						<uni-icons size="40" type="camera"></uni-icons>
					</view>
					拍摄
				</view> -->
				<!-- <view class="center ml30">
						<view class="bgf6f7f8 wh100-100 flex-ju-c mb10 ra10">
							<uni-icons size="40" type="videocam"></uni-icons>
						</view>
						视频
					</view> -->
			</view>

		</view>

	</view>
</template>

<script>
	const todo = uniCloud.importObject('my-push', {
		customUI: true,
	})
	export default {
		data() {
			return {
				imgs: '',
				showbut: false,
				content: '',
				list: [],
				top: 0,
				cid: "",
				friendinfo: {},
				page: 1,
				user: uni.getStorageSync('user'),
				glist: [],
				page: 1,
				alllist: [],
				ispage: true,
				isload: false,
				tops: ""
			};
		},
		mounted() {



		},

		onLoad(option) {
			uni.$on('globalevent', (data) => {
				var jda = data.data.payload
				if (jda.tuser.uid == this.friendinfo.uid) {
					var msgobj = {
						payload: {
							time: jda.time,
							content: jda.content,
							"type": "friend",
							messageType:jda.messageType,
							tuser: jda.tuser
						}
					}

					this.list.push(msgobj)
					this.scrollToBottom()
				}


			})

			this.glist = uni.getStorageSync('msg')
			this.friendinfo = JSON.parse(option.userinfo)
			this.getlist()

			uni.setNavigationBarTitle({
				title: this.friendinfo.nickname
			})

		},

		methods: {
			yuyins(){
				
			},
			formatTime(timestamp) {
			   
			  // 将时间戳转换为日期对象
			  var date = new Date(timestamp);
			   
			  // 获取年、月、日、小时、分钟、秒
			  var year = date.getFullYear();
			  var month = date.getMonth() + 1; // 月份是从0开始的
			  var day = date.getDate();
			  var hour = date.getHours();
			  var minute = date.getMinutes();
			  var second = date.getSeconds();
			   
			  // 格式化日期时间
			  month = month < 10 ? '0' + month : month;
			  day = day < 10 ? '0' + day : day;
			  hour = hour < 10 ? '0' + hour : hour;
			  minute = minute < 10 ? '0' + minute : minute;
			  second = second < 10 ? '0' + second : second;
			   
			  // 如果需要判断是否为当天，可以创建一个新的Date对象，并与当前日期对比
			  var today = new Date();
			  if (year == today.getFullYear() && month == (today.getMonth() + 1) && day == today.getDate()) {
			      // 是当天
							   return hour + ':' + minute
			  } else {
			      // 不是当天
							   return year + '-' + month + '-' + day + ' ' + hour + ':' + minute
			  }
			},
			preImage(item){
				console.log(item)
				var arr = []
				uni.getStorageSync('msg').map(item => {
					if (item.unid == this.user.uid) {
						item.list.map(iteg=>{
							if(iteg.tuid == this.friendinfo.uid){
								iteg.data.map(itg=>{
									if(itg.payload.messageType == 'image'){
										
										arr = [...arr,...itg.payload.content]
									}
								})
							}
						})
						
					}
				})
			
				uni.previewImage({
					current:item,
					urls: [...new Set(arr)],
				})
			},
			setimg() {
				this.upimg(9).then(res => {
					this.getimg(res)
				})
			},
			getimg(arrimg) {
				var msgobj = {
					payload: {
						time: Date.now(),
						content: arrimg,
						"type": "self",
						messageType:"image",
						tuser:this.friendinfo,
						user: this.user
					}
				}

				var ispid = false
				if (this.glist.length) {
					this.glist.map(item => {
						if (item.unid == this.user.uid) {
							for (var i = 0; i < item.list.length; i++) {
								if (item.list[i].tuid == this.friendinfo.uid) {
									item.list[i].data.push(msgobj)
									ispid = true
									break;
								}
							}
						}
					})
					if (ispid) {} else {
						this.glist.map(item => {
							if (item.unid == this.user.uid) {
								var obj = {
									allunread: 0,
									data: [{
										payload: {
											time: Date.now(),
											content: arrimg,
											"type": "self",
											messageType:"image",
											tuser: {
												avatar: this.friendinfo.avatar,
												nickname: this.friendinfo.nickname,
												uid: this.friendinfo.uid,
												uni_uid: this.friendinfo.avatar,
												mark: this.friendinfo.mark
											},
											user: this.user
										}
									}],
									tuid: this.friendinfo.uid
								}
								item.list.push(obj)
							}
						})

					}

					uni.setStorageSync('msg', this.glist)
				} else {
					var obj = {
						list: []
					}


					//判断手机登录账号
					obj.unid = uni.getStorageSync('user').uid

					obj.list.push({
						tuid: this.friendinfo.uid,
						data: [{

							payload: {
								time: Date.now(),
								content: arrimg,
								"type": "self",
								messageType:"image",
								user:this.user,
								tuser: {
									avatar: this.friendinfo.avatar,
									nickname: this.friendinfo.nickname,
									uid: this.friendinfo.uid,
									uni_uid: this.friendinfo.avatar,
									mark: this.friendinfo.mark
								}
							}


						}]
					})

					uni.setStorageSync('msg', [obj])
				}

				
				this.http('/api/deal_cid', {
					cid:uni.getStorageSync('getui_cid'),
					uid:this.friendinfo.uid,
					type:2
				},'post').then(res=>{
					
					
					this.list.push(msgobj)
					
					todo.methodq({
						content: arrimg,
						userType: 'friend',
						messageType:"image",
						alias: res.data.cid,
						user: this.user
					})
					
					this.arrimg = []
					this.$nextTick(() => {
						this.scrollToBottom()
					})
				})

				
			},
			upperthreshold(e) {
				if (this.ispage) {
					this.ispage = false
					var arrkk = this.paginate(this.alllist, 25, ++this.page)
					if (arrkk.length > 11) {
						this.isload = true
						setTimeout(() => {
							this.list = [...arrkk, ...this.list]
							this.$nextTick(() => {
								this.top = (this.list.length * 27 / (this.page - 1)) + ((this.page - 1) *
									10) + ((this.page - 2) * 60)
								this.ispage = true
							})
						}, 1000)

					} else {
						setTimeout(() => {
							this.isload = false
							this.list = [...arrkk, ...this.list]
						}, 1200)
					}

				}
			},
			getlist() {
				if (this.glist.length) {
					this.glist.map(item => {
						if (item.unid == this.user.uid) {
							item.list.map(itemd => {
								if (itemd.tuid == this.friendinfo.uid) {
									
									itemd.allunread = 0
									this.alllist = itemd.data
									this.list = this.paginate(this.alllist, 25, 1)
								}
							})
						}
					})
					uni.setStorageSync('msg', this.glist)
				}
				this.$nextTick(() => {
					this.scrollToBottom()
				})
			},
			paginate(array, page_size, page_number) {
				const start = (page_number - 1) * page_size;
				const end = page_number * page_size;
				return array.slice(-end, array.length - start);
			},
			send() {
				var msgobj = {
					payload: {
						time: Date.now(),
						content: this.content,
						"type": "self",
						tuser:this.friendinfo,
						user:this.user
					}
				}

				var ispid = false
				if (this.glist.length) {
					this.glist.map(item => {
						if (item.unid == this.user.uid) {
							for (var i = 0; i < item.list.length; i++) {
								if (item.list[i].tuid == this.friendinfo.uid) {
									item.list[i].data.push(msgobj)
									ispid = true
									break;
								}
							}
						}
					})
					if (ispid) {} else {
						this.glist.map(item => {
							if (item.unid == this.user.uid) {
								var obj = {
									allunread: 0,
									data: [{
										payload: {
											time: Date.now(),
											content: this.content,
											"type": "self",
											user:this.user,
											tuser: {
												avatar: this.friendinfo.avatar,
												nickname: this.friendinfo.nickname,
												uid: this.friendinfo.uid,
												uni_uid: this.friendinfo.avatar,
												mark: this.friendinfo.mark
											},
											user: this.user
										}
									}],
									tuid: this.friendinfo.uid
								}
								item.list.push(obj)
							}
						})

					}

					uni.setStorageSync('msg', this.glist)
				} else {
					var obj = {
						list: []
					}


					//判断手机登录账号
					obj.unid = uni.getStorageSync('user').uid

					obj.list.push({
						tuid: this.friendinfo.uid,
						data: [{

							payload: {
								time: Date.now(),
								content: this.content,
								"type": "self",
								user:this.user,
								tuser: {
									avatar: this.friendinfo.avatar,
									nickname: this.friendinfo.nickname,
									uid: this.friendinfo.uid,
									uni_uid: this.friendinfo.avatar,
									mark: this.friendinfo.mark
								}
							}


						}]
					})

					uni.setStorageSync('msg', [obj])
				}


				// 
				 
				this.http('/api/deal_cid', {
					cid:uni.getStorageSync('getui_cid'),
					uid:this.friendinfo.uid,
					type:2
				},'post').then(res=>{
					
					
					todo.methodq({
						content: this.content,
						userType: 'friend',
						alias: res.data.cid,
						user: this.user
					}).then(res=>{
						if(res.code == 5){
							uni.showModal({
								content:'发送失败，对方不在线'
							})
						}else{
							this.list.push(msgobj)
							this.content = ''
							this.$nextTick(() => {
								this.scrollToBottom()
							})
						}
						
					}).catch(res=>{
						uni.showModal({
							content:JSON.stringify(res)
						})
					})
					
					
					
				})
				 
				

			},
			chooseImage() {
				this.showbut = !this.showbut
				return
				uni.chooseImage({
					// sourceType: 'album',
					success: (res) => {
						this.list.push({
							content: res.tempFilePaths[0],
							userType: 'self',
							messageType: 'image',
							avatar: this._selfAvatar
						})
						this.scrollToBottom()
						// 模拟对方回复
						setTimeout(() => {
							this.list.push({
								content: '你好呀，朋友~',
								userType: 'friend',
								avatar: this._friendAvatar
							})
							this.scrollToBottom()
						}, 1500)
					}
				})
			},
			scrollToBottom() {
				this.top = this.list.length * 1000
			}
		}
	}
</script>

<style lang="scss" scoped>
	.scroll-view {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		background: #f6f7f8;
		box-sizing: border-box;
	}

	.message {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
			margin-right: 30rpx;
		}

		.content {
			min-height: 80rpx;
			max-width: 60vw;
			box-sizing: border-box;
			font-size: 28rpx;
			line-height: 1.3;
			padding: 20rpx;
			border-radius: 10rpx;
			background: #fff;

			image {
				width: 250rpx;
			}
		}

		&.self {
			justify-content: flex-end;

			.avatar {
				margin: 0 0 0 30rpx;
			}

			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-left: 16rpx solid #fff;
					right: -28rpx;
					top: 24rpx;
				}
			}
		}

		&.friend {
			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-right: 16rpx solid #fff;
					left: -28rpx;
					top: 24rpx;
				}
			}
		}
	}

	.tool {
		position: fixed;
		width: 100%;
		left: 0;
		align-items: center;
		bottom: 0px;
		background: #fff;
		// display: flex;
		box-sizing: border-box;
		padding: 20rpx;

		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;

		.input {
			background: #f6f7f8;
			border-radius: 10rpx;
			// min-height: 70rpx;
			padding: 10px;
			margin-right: 20rpx;
			flex: 1;
			box-sizing: border-box;
			font-size: 28rpx;
		}

		.thumb {
			width: 64rpx;
		}
	}
</style>